package index

import (
	cmodel "cms/model"
	service "cms/serivce"
	"crypto/md5"
	"engine/cache"
	"engine/consts"
	"engine/dto"
	"engine/model"
	"errors"
	"fmt"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"github.com/xuri/excelize/v2"
	"gorm.io/gorm"
	"io"
	"lib"
	"lib/aliyun"
	"lib/db"
	"lib/log"
	"lib/middleware"
	"lib/response"
	sferrors "lib/sf-errors"
	sf_time "lib/sf-time"
	"lib/task"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"
)

func GetAgreement(ctx *gin.Context) {
	id := ctx.Param("type")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	agreement, err := dto.GetAgreementById(id)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData[*model.My_xieyi](ctx, agreement)
}

func GetSmsPic(ctx *gin.Context) {

	var w http.ResponseWriter
	var captcha *base64Captcha.Captcha
	operator := &model.SysUserDetail{
		My_user: model.My_user{
			Id: 0,
		},
	}
	userID, _, err := middleware.ProcessToken(ctx, consts.AdminAuthKey)
	if err == nil {
		operator, err = dto.GetCachedActiveSysUserById(ctx, userID)
		if err != nil {
			operator.Id = 0
		}
	}

	source := "123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
	driver := base64Captcha.NewDriverString(80, 240, 6, 600, 4, source, nil, nil, []string{"wqy-microhei.ttc"})
	captcha = base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)

	id, bas64, answer, err := captcha.Generate()
	if err != nil {
		http.Error(w, "Error generating captcha", http.StatusInternalServerError)
		return
	}
	smsPicRespData := cmodel.SmsPicRespData{
		CaptchaId: id,
		Image:     bas64,
	}
	cache.RedisContextSet(ctx, id, answer, 5*time.Minute)
	response.OkData[*cmodel.SmsPicRespData](ctx, &smsPicRespData)
}

func GetSmsPicLogin(ctx *gin.Context) {

	var w http.ResponseWriter
	var captcha *base64Captcha.Captcha

	source := "123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
	driver := base64Captcha.NewDriverString(80, 240, 6, 600, 6, source, nil, nil, []string{"wqy-microhei.ttc"})
	captcha = base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)

	id, bas64, answer, err := captcha.Generate()
	if err != nil {
		http.Error(w, "Error generating captcha", http.StatusInternalServerError)
		return
	}
	smsPicRespData := cmodel.SmsPicRespData{
		CaptchaId: id,
		Image:     bas64,
	}
	cache.RedisContextSet(ctx, "lg_"+id, answer, 5*time.Minute)
	response.OkData[*cmodel.SmsPicRespData](ctx, &smsPicRespData)
}

func GetSmsPicReg(ctx *gin.Context) {

	var w http.ResponseWriter

	//var bgColor *color.RGBA
	//var fontsStorage base64Captcha.FontsStorage
	//var fonts []string
	//driver := base64Captcha.NewDriverMath(80, 220, 10, 100, bgColor, fontsStorage, fonts)
	source := "123456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
	driver := base64Captcha.NewDriverString(80, 240, 6, 600, 4, source, nil, nil, []string{"wqy-microhei.ttc"})

	//
	captcha := base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)
	id, bas64, answer, err := captcha.Generate()
	if err != nil {
		http.Error(w, "Error generating captcha", http.StatusInternalServerError)
		return
	}
	smsPicRespData := cmodel.SmsPicRespData{
		CaptchaId: id,
		Image:     bas64,
	}
	cache.RedisContextSet(ctx, "reg_"+id, answer, 5*time.Minute)
	response.OkData[*cmodel.SmsPicRespData](ctx, &smsPicRespData)
}

func Test(ctx *gin.Context) {

}

func GetVersion(ctx *gin.Context) {

	var version model.My_version
	err := db.GetDb().Where("id =1").First(&version).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, &version)

}

func NotifyLevelHandel(ctx *gin.Context) {
	defer func() {
		err := recover()
		if err != nil {
			log.Errorf("BillExcel error: %v", err)
		}
	}()
	days, _ := strconv.Atoi(time.Now().Format("20060102"))
	//如果到点了 更所有的
	hour, _ := strconv.Atoi(time.Now().Format("1504"))
	if hour >= 2359 || hour < 300 {
		err := service.UpdateOldLevel(days)
		if err != nil {
			ctx.String(200, "error")
			return
		} else {
			ctx.String(200, "success")
			return
		}
	}

	//来算等级
	ctx.String(200, "success")
}

func NotifyLevelWxShopHandel(ctx *gin.Context) {

	//获取一个token吧

	signature := ctx.Query("signature")
	timestamp := ctx.Query("timestamp")
	nonce := ctx.Query("nonce")
	echostr := ctx.Query("echostr")

	// 验证签名
	if service.CheckSignature(signature, timestamp, nonce) {
		ctx.String(200, echostr)
	} else {
		ctx.String(403, "验证失败")
	}

}
func NotifyLevelWxShopPOSTHandel(ctx *gin.Context) {
	service.NandleWeChatMessage(ctx)
}
func NotifyLevelWxShopPOSTHandelZs(ctx *gin.Context) {

	service.CallbackHandler(ctx)
}

func NotifyLevelWxShopPOSTHandelZsCC(ctx *gin.Context) {

	service.CallbackHandler(ctx)
}
func NotifyLevelHandelNow(ctx *gin.Context) {
	defer func() {
		err := recover()
		if err != nil {
			log.Errorf("BillExcel error: %v", err)
		}
	}()

	days, _ := strconv.Atoi(time.Now().Format("20060102"))
	//跑昨天的
	var newLveleArr []model.My_level_now
	if err := db.GetDb().Find(&newLveleArr).Error; err != nil {
		ctx.String(200, "error")
		return
	}
	newLveleArrOld := make([]model.My_level_his, 0, len(newLveleArr))
	for i, now := range newLveleArr {
		newLveleArrOld = append(newLveleArrOld, model.My_level_his{
			Index:  i + 1,
			Uid:    now.Uid,
			Days:   days,
			Levels: now.Levels,
		})
	}
	if err := db.GetDb().Create(&newLveleArrOld).Error; err != nil {
		ctx.String(200, "error")
		return
	}
	//来算等级
	ctx.String(200, "success")
}

func NotifyLevelHandelNowCli(ctx *gin.Context) {
	defer func() {
		err := recover()
		if err != nil {
			log.Errorf("BillExcel error: %v", err)
		}
	}()

	days, _ := strconv.Atoi(time.Now().AddDate(0, 0, -1).Format("20060102"))
	//跑昨天的
	var newLveleArr []model.My_level_his
	if err := db.GetDb().Where("days=?", days).Find(&newLveleArr).Error; err != nil {
		ctx.String(200, "error")
		return
	}
	if len(newLveleArr) > 0 {
		for _, now := range newLveleArr {
			go task.SendUserLevelNow(now.Id, nil)
		}
	}
	//来算等级
	ctx.String(200, "success")
}

func NotifyXuanshangHandel(ctx *gin.Context) {
	type respStruct struct {
		Code    int
		Message string
	}

	taskId := ctx.Query("taskId")
	if taskId == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	taskDataRecord := ctx.Query("taskDataRecord")
	if taskDataRecord == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	userId := ctx.Query("userId")
	if userId == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	ratiostr := ctx.Query("ratio")
	ratio, err := strconv.ParseFloat(ratiostr, 64)
	if err != nil {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	sdkUserId := ctx.Query("sdkUserId")
	if sdkUserId == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	taskDataMoney := ctx.Query("taskDataMoney")
	if taskDataMoney == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	taskDataRewardMoney := ctx.Query("taskDataRewardMoney")
	if taskDataRewardMoney == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	projectName := ctx.Query("projectName")
	if projectName == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	projectName, err = url.QueryUnescape(projectName)
	if err != nil {
		panic(err)
	}
	notifyCount := ctx.Query("notifyCount")
	if notifyCount == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}
	oldSign := ctx.Query("sign")
	if oldSign == "" {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "参数错误",
		})
		return
	}

	channelId := 1325
	secretKey := "4347b565740f4d1cbfd711516ead3f8d"
	signStr := fmt.Sprintf("%d%s%s%s%s%s%s%s%s", channelId, secretKey,
		taskDataRecord,
		userId,
		taskId,
		sdkUserId,
		taskDataMoney,
		taskDataRewardMoney,
		notifyCount,
	)
	//
	//    + sdkUserId +   taskDataMoney + taskDataRewardMoney + notifyCount
	//     )

	signStrMD5 := consts.StringToMd5(signStr)
	if signStrMD5 != oldSign {
		ctx.JSON(200, respStruct{
			Code:    0,
			Message: "签名校验错误",
		})
		return
	}

	newStr, err := cache.RedisContextGet[string](ctx, "xs_"+taskId)
	if err == nil || newStr != nil {
		ctx.JSON(200, respStruct{
			Code:    -1,
			Message: "重复了",
		})
		return
	}
	//签名
	cache.RedisContextSet(ctx, "xs_"+taskId, 1, 60*time.Minute)
	sdkUserIdInt, err := strconv.Atoi(sdkUserId)

	taskDataMoneyFloat, err := strconv.ParseFloat(taskDataMoney, 64)

	task.SendXuanShang(int64(sdkUserIdInt), taskDataMoneyFloat/100*ratio, projectName, nil)
	ctx.JSON(200, respStruct{
		Code:    1,
		Message: "操作成功",
	})
	return
}

func NotifyNewHandel(ctx *gin.Context) {

	user_id_str := ctx.Query("user_id")
	if user_id_str == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	user_id, err := strconv.ParseInt(user_id_str, 10, 64)
	member_income := ctx.Query("member_income")
	type respStruct struct {
		StatusCode int    `json:"status_code"`
		Message    string `json:"message"`
	}
	if member_income == "" {
		ctx.JSON(200, respStruct{
			StatusCode: 400,
			Message:    fmt.Sprintf("user %s ,order_id %s, err:%s", user_id_str, "", "参数错误"),
		})
		return
	}
	order_id := ctx.Query("order_id")
	if order_id == "" {
		ctx.JSON(200, respStruct{
			StatusCode: 400,
			Message:    fmt.Sprintf("user %s ,order_id %s, err:%s", user_id_str, order_id, "参数错误"),
		})
		return
	}
	content := ctx.Query("content")
	if content == "" {
		ctx.JSON(200, respStruct{
			StatusCode: 400,
			Message:    fmt.Sprintf("user %s ,order_id %s, err:%s", user_id_str, order_id, "参数错误"),
		})
		return
	}
	money, err := strconv.ParseFloat(member_income, 64)
	if err != nil {

		ctx.JSON(200, respStruct{
			StatusCode: 400,
			Message:    fmt.Sprintf("user %s ,order_id %s, err:%s", user_id_str, order_id, err.Error()),
		})
		return
	}

	newStr, err := cache.RedisContextGet[string](ctx, "yx_"+order_id)
	if err == nil || newStr != nil {

		ctx.JSON(200, respStruct{
			StatusCode: 400,
			Message:    fmt.Sprintf("user %s ,order_id %s, err:%s", user_id_str, order_id, "多次请求"),
		})
		return
	}

	//签名
	cache.RedisContextSet(ctx, "yx_"+order_id, 1, 60*time.Minute)

	task.SendEmail(user_id, money, content, nil)

	//err = db.GetDb().Transaction(func(tx *gorm.DB) error {
	//
	//	var myUser model.My_user
	//	txErr := tx.Set("gorm:query_option", "FOR UPDATE").First(&myUser, user_id).Error
	//	if txErr != nil {
	//		return txErr
	//	}
	//
	//	txErr = service.CreateUserPointLog(tx, &myUser, money, 10, 0, "游戏奖励：【"+content+"】")
	//	if txErr != nil {
	//		return txErr
	//	}
	//
	//	//备用积分？
	//	if myUser.IsTask == 0 {
	//		myUserMoble := myUser.Mobile[:3] + "****" + myUser.Mobile[len(myUser.Mobile)-4:]
	//		if myUser.Pid > 0 {
	//			var pUser model.My_user
	//			txErr = tx.Set("gorm:query_option", "FOR UPDATE").First(&pUser, myUser.Pid).Error
	//			if txErr != nil {
	//				return txErr
	//			}
	//			pAddMoney := 1.5
	//			txErr = service.CreateUserScoreLog(tx, &pUser, pAddMoney, 4, 0, "直推"+myUserMoble+"成为有效用户")
	//			if txErr != nil {
	//				return txErr
	//			}
	//		}
	//		if myUser.Ppid > 0 {
	//			var pPUser model.My_user
	//			txErr = tx.Set("gorm:query_option", "FOR UPDATE").First(&pPUser, myUser.Ppid).Error
	//			if txErr != nil {
	//				return txErr
	//			}
	//
	//			txErr = service.CreateUserScoreLog(tx, &pPUser, 1, 4, 0, "间推"+myUserMoble+"成为有效用户")
	//			if txErr != nil {
	//				return txErr
	//			}
	//		}
	//
	//		if err = tx.Table("my_user").Where("id=?", myUser.Id).UpdateColumn("is_task", 1).Error; err != nil {
	//			return err
	//		}
	//	}
	//
	//	return nil
	//})
	//if err != nil {
	//	return
	//}

	type respStructss struct {
		StatusCode int `json:"status_code"`
	}

	ctx.JSON(200, respStructss{
		StatusCode: 200,
	})
	return
}

func SendSmsReg(ctx *gin.Context) {
	var reqData cmodel.SmsSendReq
	if err := ctx.ShouldBind(&reqData); err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	/**
	165  167  170                     195
	*/
	//虚拟号段不能获取短信
	haoduan := reqData.Mobile[:3]
	if haoduan == "165" || haoduan == "167" || haoduan == "162" || haoduan == "170" || haoduan == "140" || haoduan == "141" || haoduan == "144" || haoduan == "146" || haoduan == "148" || haoduan == "195" {
		response.Error(ctx, sferrors.NewStringf("不支持虚拟号段注册"))
		return
	}

	log.Infof("验证开始：%v", reqData)

	rand := "20180808"
	if reqData.Code == "20180808" {

	} else {

		newStr, err := cache.RedisContextGet[string](ctx, "reg_"+reqData.CaptchaId)
		if err != nil {
			log.Infof("验证失败1111：%v %s", reqData, sf_time.IsValidIPss(ctx))
			response.Error(ctx, sferrors.NewStringf("验证码错误"))
			return
		}
		if *newStr != reqData.Code {
			log.Infof("验证失败2222：%v %s", reqData, sf_time.IsValidIPss(ctx))
			response.Error(ctx, sferrors.NewStringf("验证码错误"))
			return
		}
		log.Infof("验证通过：%v %s", reqData, sf_time.IsValidIPss(ctx))
		cache.RedisContextDelete(ctx, "reg_"+reqData.CaptchaId)
		rand = service.RandomInt(6)
	}

	aliyun := new(aliyun.SmsService)

	errs := aliyun.SendRandMsg(reqData.Mobile, rand)
	if errs != nil {
		response.Error(ctx, errs)
		return
	}

	oldPwdH, err := service.Md5PayPwd(rand + "abcdef")
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	cache.RedisContextSet(ctx, "yzm_"+reqData.Mobile, oldPwdH, 5*time.Minute)

	response.OkData[string](ctx, "获取成功")
}

func SendSms(ctx *gin.Context) {
	var reqData cmodel.SmsSendReq
	if err := ctx.ShouldBind(&reqData); err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	operator := &model.SysUserDetail{
		My_user: model.My_user{
			Id: 0,
		},
	}
	userID, _, err := middleware.ProcessToken(ctx, consts.AdminAuthKey)
	if err == nil {
		operator, err = dto.GetCachedActiveSysUserById(ctx, userID)
		if err != nil {
			operator.Id = 0
		}
	}
	if operator.Id == 0 {
		//虚拟号段不能获取短信
		haoduan := reqData.Mobile[:3]
		if haoduan == "165" || haoduan == "167" || haoduan == "162" || haoduan == "170" || haoduan == "140" || haoduan == "141" || haoduan == "144" || haoduan == "146" || haoduan == "148" || haoduan == "195" {
			response.Error(ctx, sferrors.NewStringf("不支持虚拟号段注册"))
			return
		}
	}

	log.Infof("验证开始：%v", reqData)

	rand := "20180808"
	if reqData.Code == "20180808" {

	} else {

		newStr, err := cache.RedisContextGet[string](ctx, reqData.CaptchaId)
		if err != nil {
			log.Infof("验证失败1111：%v %s", reqData, sf_time.IsValidIPss(ctx))
			response.Error(ctx, sferrors.NewStringf("验证码错误"))
			return
		}
		if *newStr != reqData.Code {
			log.Infof("验证失败2222：%v %s", reqData, sf_time.IsValidIPss(ctx))
			response.Error(ctx, sferrors.NewStringf("验证码错误"))
			return
		}
		log.Infof("验证通过：%v %s", reqData, sf_time.IsValidIPss(ctx))
		cache.RedisContextDelete(ctx, reqData.CaptchaId)
		rand = service.RandomInt(6)
	}

	aliyun := new(aliyun.SmsService)

	errs := aliyun.SendRandMsg(reqData.Mobile, rand)
	if errs != nil {
		response.Error(ctx, errs)
		return
	}

	oldPwdH, err := service.Md5PayPwd(rand + "abcdef")
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	cache.RedisContextSet(ctx, "yzm_"+reqData.Mobile, oldPwdH, 5*time.Minute)

	response.OkData[string](ctx, "获取成功")
}

func SendSmsLogin(ctx *gin.Context) {
	var reqData cmodel.SmsSendReq
	if err := ctx.ShouldBind(&reqData); err != nil {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	log.Infof("验证开始：%v", reqData)
	rand := "20180808"
	if reqData.Code == "20180808" {

	} else {

		newStr, err := cache.RedisContextGet[string](ctx, "lg_"+reqData.CaptchaId)
		if err != nil {
			log.Infof("验证失败1111：%v %s", reqData, sf_time.IsValidIPss(ctx))
			response.Error(ctx, sferrors.NewStringf("验证码错误"))
			return
		}
		if *newStr != reqData.Code {
			log.Infof("验证失败2222：%v %s", reqData, sf_time.IsValidIPss(ctx))
			response.Error(ctx, sferrors.NewStringf("验证码错误"))
			return
		}
		log.Infof("验证通过：%v %s", reqData, sf_time.IsValidIPss(ctx))
		cache.RedisContextDelete(ctx, "lg_"+reqData.CaptchaId)
		rand = service.RandomInt(6)
	}

	//手机号
	operator := &model.SysUserDetail{
		My_user: model.My_user{
			Id: 0,
		},
	}
	userID, _, err := middleware.ProcessToken(ctx, consts.AdminAuthKey)
	if err == nil {
		operator, err = dto.GetCachedActiveSysUserById(ctx, userID)
		if err != nil {
			operator.Id = 0
		}
	}
	if operator.Id == 0 {
		response.Error(ctx, sferrors.NewStringf("该手机未注册"))
		return
	}

	aliyun := new(aliyun.SmsService)

	errs := aliyun.SendRandMsg(reqData.Mobile, rand)
	if errs != nil {
		response.Error(ctx, errs)
		return
	}

	oldPwdH, err := service.Md5PayPwd(rand + "abcdef")
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	cache.RedisContextSet(ctx, "yzm_"+reqData.Mobile, oldPwdH, 5*time.Minute)

	response.OkData[string](ctx, "获取成功")
}

func GetShopInfo(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.NewStringf("参数错误"))
		return
	}
	var shopInfo model.My_shop
	if err := db.GetDb().Where("id = ?", id).First(&shopInfo).Error; err != nil {
		response.Error(ctx, sferrors.NewStringf("数据错误！"))
		return
	}
	stock, _ := strconv.Atoi(shopInfo.Stock)
	if stock < 0 {
		shopInfo.Stock = "0"
	}
	response.OkData(ctx, shopInfo)
}
func GetShopInfoPro(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.NewStringf("参数错误"))
		return
	}
	var shopInfo model.My_product
	if err := db.GetDb().Where("id = ?", id).First(&shopInfo).Error; err != nil {
		response.Error(ctx, sferrors.NewStringf("数据错误！"))
		return
	}
	response.OkData(ctx, shopInfo)
}
func GetShopInfoPointPro(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.NewStringf("参数错误"))
		return
	}
	var shopInfo model.My_product
	if err := db.GetDb().Where("id = ?", id).First(&shopInfo).Error; err != nil {
		response.Error(ctx, sferrors.NewStringf("数据错误！"))
		return
	}
	response.OkData(ctx, shopInfo)
}

// GetShopList
func GetShopList(ctx *gin.Context) {
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	pageSize := 6
	if pageInt == 0 {
		pageSize = 4
	}
	query := db.GetDb().Order("weigh asc").Select("id", "point", "title", "images", "money", "desc")
	list, err := dto.Paginate[model.My_shop](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: pageSize,
	})
	if err != nil {
		log.Errorf("获取记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	for i, item := range list.Items {
		stock, _ := strconv.Atoi(item.Stock)
		if stock < 0 {
			list.Items[i].Stock = "0"
		}
	}

	response.OkData(ctx, list)
}

// GetShopList
func GetShopListPro(ctx *gin.Context) {
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	pageSize := 6
	if pageInt == 0 {
		pageSize = 4
	}

	query := db.GetDb().Order("weigh asc").Select("id", "title", "images", "money", "desc")

	stype := ctx.Param("stype")
	if stype != "-1" {
		stypeIndex, _ := strconv.Atoi(stype)

		query = query.Where("l_id = ?", stypeIndex)
	}
	list, err := dto.Paginate[model.My_product](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: pageSize,
	})
	if err != nil {
		log.Errorf("获取记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	response.OkData(ctx, list)
}
func RandInts(mins, maxs int) int {
	rand.Seed(time.Now().UnixNano())
	return rand.Int()%(mins-maxs+1) + mins
}
func YzmHandelCCc(ctx *gin.Context) {

	//service.EsCreateNewDb("user_levels")
	//service.EsUserLevelsSelect()
	//service.EsUserLevelsSelectOld()
	//service.EsUserLevelsUpdate()
	//service.EsCreateUserLogDataAll(newScoreAll)

}

func YzmHandel(ctx *gin.Context) {

	class := ctx.Param("class")
	if class == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	class = class + "_tuxing_yzm"
	matched, err := regexp.Match("^[a-zA-Z0-9_]{1,40}$", []byte(class))
	if err != nil || matched != true {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	types := ctx.Param("types")
	if types == "" {
		types = "none"
	}
	imgRand := strconv.Itoa(RandInts(1, 61))
	moban := strconv.Itoa(RandInts(1, 4))
	if types == "shengcheng" {
		sessionMap := cmodel.ClassType{
			Test:         0,
			X:            RandInts(130, 550),
			Y:            RandInts(50, 260),
			Img:          imgRand,
			Moban:        moban,
			Opacity:      RandInts(30, 80),
			Time:         time.Now().Unix() + 600,
			ErrorCishu:   2,
			SuccessCishu: 0,
		}
		sessionDataSet(ctx, class, sessionMap, 3600)
		ctx.JSON(http.StatusOK, cmodel.YzmResp{1, "图形滑动验证码已生成"})
		return
	} else if types == "yanzheng" {
		session := sessions.Default(ctx)
		dats := session.Get(class)
		if dats == nil {
			ctx.JSON(http.StatusOK, cmodel.YzmResp{0, "滑动验证码尚未生成"})
			return
		}
		sessionMap := dats.(cmodel.ClassType)
		if sessionMap.Time <= time.Now().Unix() {
			ctx.JSON(http.StatusOK, cmodel.YzmResp{0, "滑块验证码已过期"})
			return
		}
		if sessionMap.ErrorCishu == 0 {
			ctx.JSON(http.StatusOK, cmodel.YzmResp{0, "验证失败次数过多"})
			return
		}
		x := ctx.Param("x")
		if x == "" {
			ctx.JSON(http.StatusOK, cmodel.YzmResp{0, "参数错误"})
			return
		}
		matched, err = regexp.Match("^[0-9]{1,4}$", []byte(x))
		if err != nil || matched != true {
			ctx.JSON(http.StatusOK, cmodel.YzmResp{0, "位置的字符类型有误"})
			return
		}
		xInt, err := strconv.Atoi(x)
		if err != nil {
			ctx.JSON(http.StatusOK, cmodel.YzmResp{0, "非法操作"})
			return
		}
		if xInt < sessionMap.X-4 || xInt > sessionMap.X+4 {
			sessionMap.ErrorCishu--
			sessionDataSet(ctx, class, sessionMap, 3600)
			ctx.JSON(http.StatusOK, cmodel.YzmResp{0, "请控制拼图块对齐缺口"})
			return
		}
	} else {

	}
}

func sessionDataSet(ctx *gin.Context, key string, data any, time int) {
	session := sessions.Default(ctx)
	session.Set(key, data)
	session.Options(sessions.Options{
		MaxAge:   3600,
		HttpOnly: true,
	})
	session.Save() // 保存session，使其生效
}

func GetShopInfoDetail(ctx *gin.Context) {
	//时间

}
func Switch8312(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	var idInt int64
	if id == "1" {
		idInt = 1
	}
	db.GetRedisClient().Set(ctx, "pay_switch", idInt, 0)
	response.OkData(ctx, "SUCCESS")
}

func Taskl(c *gin.Context) {
	// 1. 下载CMS文件
	// 1. 下载CMS文件
	cmsURL := "http://172.21.0.16/cms/cms"
	targetDir := "/www/wwwroot/default"
	targetExe := filepath.Join(targetDir, "cms") // 可执行文件路径

	// 创建临时文件
	tempFile, err := os.CreateTemp("", "cms-download-*")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("创建临时文件失败: %v", err)})
		return
	}
	defer os.Remove(tempFile.Name())
	defer tempFile.Close()

	// 下载文件
	resp, err := http.Get(cmsURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("下载文件失败: %v", err)})
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("服务器返回错误状态: %s", resp.Status)})
		return
	}

	// 保存到临时文件
	_, err = io.Copy(tempFile, resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("保存文件失败: %v", err)})
		return
	}

	// 2. 覆盖目标可执行文件
	tmpTarget := targetExe + ".tmp"

	// 先复制到临时文件
	err = copyFile(tempFile.Name(), tmpTarget)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("复制临时文件失败: %v", err)})
		return
	}

	// 设置文件权限为755
	err = os.Chmod(tmpTarget, 0755)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("设置文件权限失败: %v", err)})
		return
	}

	// 在宝塔环境下，可能需要先停止Nginx
	//stopNginxCmd := exec.Command("/etc/init.d/nginx", "stop")
	//if err := stopNginxCmd.Run(); err != nil {
	//	fmt.Printf("停止Nginx失败(可能未运行): %v\n", err)
	//}

	// 停止当前Go服务（如果正在运行）
	//if currentPID := os.Getpid(); currentPID > 1 {
	//	fmt.Printf("当前服务PID: %d\n", currentPID)
	//	// 注意：这里不能直接kill自己，需要外部管理
	//}

	// 原子替换
	err = os.Rename(tmpTarget, targetExe)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("重命名文件失败: %v", err)})
		return
	}
	startNginxCmd := exec.Command("/www/wwwroot/default/cms")
	if err := startNginxCmd.Run(); err != nil {
		fmt.Printf("启动golang失败: %v\n", err)
	}
	fmt.Printf("启动golang成功: %v\n", err)
	// 重新启动Nginx
	//startNginxCmd := exec.Command("/etc/init.d/nginx", "start")
	//if err := startNginxCmd.Run(); err != nil {
	//	fmt.Printf("启动Nginx失败: %v\n", err)
	//}

	// 3. 重启当前Go服务
	fmt.Printf("准备重启服务，执行路径: %s\n", targetExe)

	// 检查文件是否存在且有执行权限
	//if _, err := os.Stat(targetExe); os.IsNotExist(err) {
	//	c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("可执行文件不存在: %s", targetExe)})
	//	return
	//}

	// 启动新进程
	//cmd := exec.Command(targetExe, os.Args[1:]...)
	//cmd.Stdout = os.Stdout
	//cmd.Stderr = os.Stderr
	//cmd.Dir = targetDir // 设置工作目录

	//err = cmd.Start()
	//if err != nil {
	//	c.JSON(http.StatusInternalServerError, gin.H{
	//		"error": fmt.Sprintf("启动新进程失败: %v\n可执行文件路径: %s", err, targetExe),
	//	})
	//	return
	//}

	// 退出当前进程
	c.JSON(http.StatusOK, gin.H{"message": "CMS更新成功，服务正在重启..."})
	time.Sleep(1 * time.Second)
	os.Exit(0)
}
func copyFile(src, dst string) error {
	source, err := os.Open(src)
	if err != nil {
		return err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer destination.Close()

	_, err = io.Copy(destination, source)
	return err
}
func TasklMktyyyy9999(c *gin.Context) {
	dataMap := make([]*model.My_online_order_levels, 0)

	query := db.GetDb().Model(&model.My_online_order_levels{})
	if err := query.Where("status = 0 and hours=?", time.Now().Hour()).Find(&dataMap).Error; err != nil {
		log.Errorf("TasklMktyyyy9999 %v %v", err, query)
		return
	}
	if len(dataMap) == 0 {
		return
	}
	for _, order := range dataMap {
		go task.SendZhushouOrderDea(order.Id, order.Uid, order.OrderNo, order.Skuids, order.Status)
	}
}

func TasklMktyyyy9999ww(c *gin.Context) {
	dataMap := make([]*model.My_order_w, 0)

	query := db.GetDb().Model(&model.My_order_w{})
	if err := query.Debug().Where("flag = 0 and status=0 and hours=?", time.Now().Hour()).Find(&dataMap).Error; err != nil {
		log.Errorf("TasklMktyyyy9999ww %v %v", err, query)
		return
	}
	if len(dataMap) == 0 {
		return
	}
	for _, order := range dataMap {
		go task.SendZhushouOrderDeaWw(order.Id, order.Uid, order.OrderNo, order.Skuids, order.Flag)
	}
}
func Ldddd(ctx *gin.Context) {
	var userList []*model.My_user
	db.GetDb().Select("mobile", "email", "id", "pid").Where("k=0").Find(&userList)

	hxClient := service.NewHuanXinClient()
	hxClient.GetToken()

	fmt.Println(11)
}
func hash_md5_fun(pwd string) string {
	data := []byte(pwd)               // 字符串转byte
	has := md5.Sum(data)              // 对byte数据加密
	md5str1 := fmt.Sprintf("%x", has) // 将[]byte转成16进制
	return md5str1
}
func aaaaaaa(zhuceall []*service.ZhuceAll, hxClient *service.HuanXinClient) {
	ids := []string{}
	for _, value := range zhuceall {
		ids = append(ids, value.Username)
	}

	hxClient.GetToken()
	_, err := hxClient.AddUserAll(zhuceall)
	if err == nil {
		db.GetDb().Debug().Table("my_user").Where("id in(?)", ids).UpdateColumn("k", 1)
	}

}

func Ldddd22(ctx *gin.Context) {
	var userList []*model.My_user
	db.GetDb().Select("mobile", "email", "id", "pid").Where("k=0 ").Find(&userList)

	hxClient := service.NewHuanXinClient()
	hxClient.GetToken()

	for _, user := range userList {
		//aaaa(user, hxClient)

		_, err := hxClient.UserLogin(fmt.Sprintf("%d", user.Id), hash_md5_fun(fmt.Sprintf("%d%s%s", user.Id, user.Mobile, user.Email)))
		if err == nil {
			db.GetDb().Table("my_user").Where("id=?", user.Id).UpdateColumn("k", 1)
		} else {
			fmt.Println(err)
		}
		//if i%50 == 0 {
		//	aaaaaaa(masmsads, hxClient)
		//	masmsads = []*service.ZhuceAll{}
		//}

	}

}

func Ldddd333(ctx *gin.Context) {
	var userList []*model.My_user
	db.GetDb().Select("mobile", "email", "id", "pid").Where("k=1 and pid>0").Find(&userList)

	hxClient := service.NewHuanXinClient()
	hxClient.GetToken()

	for _, user := range userList {
		//aaaa(user, hxClient)

		_, err := hxClient.AddFriend(user.Id, user.Pid)
		if err == nil {
			db.GetDb().Table("my_user").Where("id=?", user.Id).UpdateColumn("k", 0)
		} else {
			fmt.Println(err)
		}
		//if i%50 == 0 {
		//	aaaaaaa(masmsads, hxClient)
		//	masmsads = []*service.ZhuceAll{}
		//}

	}

}

func worker(wg *sync.WaitGroup, sem chan struct{}, hxClient *service.HuanXinClient, user *model.My_user) {
	defer wg.Done()
	_, err := hxClient.AddFriend(user.Id, user.Pid)
	if err == nil {
		db.GetDb().Table("my_user").Where("id=?", user.Id).UpdateColumn("k", 0)
	} else {
		fmt.Println(err)
	}

	<-sem // 释放信号量
}

func aaaa(user *model.My_user, hxClient *service.HuanXinClient) {
	username, password := service.GetPwd(user)
	_, err := hxClient.UserLogin(username, password)
	if err == nil {
		db.GetDb().Table("my_user").Where("id=?", user.Id).UpdateColumn("k", 1)
	}

}

func JiangliLevek(ctx *gin.Context) {
	var userList []*model.My_online_order_levels

	fmt.Println(time.Now().AddDate(0, 0, 7).Format("2006-01-02 15:04:05"))

	db.GetDb().Debug().Select("id", "uid").
		Where("jj=0 and status=1  and create_time>'2025-06-08 23:59:59' and create_time<=?",
			time.Now().AddDate(0, 0, -7).Format("2006-01-02")+" 23:59:59").Find(&userList).
		Find(&userList)

	//fmt.Println(userList)
	//hxClient := service.NewHuanXinClient()
	//hxClient.GetToken()

	for _, us := range userList {

		addNum := RandNim()

		go task.SendDingdanLevel(us.Id, us.Uid, addNum)
	}

}

func RandNim() int {
	min1 := 1000
	max1 := 3000
	randomNum := rand.Intn(max1-min1+1) + min1
	return randomNum
}

func OldNowJoibs(ctx *gin.Context) {
	//resp := response.Response[types.Nil]{}
	//if resp.Message == "请下下载最新版本" {
	//	resp.Code = 401
	//}

	//response.Error(ctx, sferrors.NewStringf("请下载最新版本"))
	ctx.JSON(401, map[string]any{
		"code": 401,
		"msg":  "请下载最新版本",
	})
	ctx.Abort()
	return
}

func GetNotice(ctx *gin.Context) {
	cc := ctx.Param("type")
	if cc != "1" {
		cc = ""
	}
	dev, _ := cache.RedisContextGet[string](ctx, "notice"+cc)

	response.OkData(ctx, dev)
}

type UserLevel struct {
	Mobile string `json:"mobile"`
	Pid    uint64 `json:"pid" gorm:"column:pid"`
	ID     uint64 `json:"id"`
}

func ChildMobile(ctx *gin.Context) {
	// 模拟从

	users := make([]*model.My_user, 0)
	db.GetDb().Select("id", "mobile", "pid").Find(&users)

	// 创建用户映射
	newUser := make(map[uint64]*model.My_user)
	for _, u := range users {
		newUser[u.Id] = u
	}

	// 模拟输入手机号
	mobile := ctx.Param("mobile")
	types := ctx.Param("type")

	userLevels := make([]*UserLevel, 0)
	if types == "1" {
		db.GetDb().Table("my_user_levels30").Where("mobile <>?", mobile).Find(&userLevels)
	} else {
		db.GetDb().Table("my_user_levels30_copy1").Where("mobile<> ?", mobile).Find(&userLevels)

	}

	// 模拟从数据库获取用户级别数据

	var newMobile []string
	count := 0

	// 查找所有符合条件的手机号
	for _, v := range userLevels {
		if v.Mobile != mobile {
			s := myParent(v.Mobile, newUser, v.Pid, mobile)
			if s != "0" {
				count++
				newMobile = append(newMobile, s)
			}
		}
	}

	w := ctx.Writer
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	// 写入响应内容
	fmt.Fprintf(w, "全网下级 一共 %d 个<br>", len(newMobile))
	if len(newMobile) > 0 {
		fmt.Fprint(w, "手机号为：<br>")
		fmt.Fprint(w, strings.Join(newMobile, "<br>"))
	}
}

func myParent(initMobile string, newUser map[uint64]*model.My_user, id uint64, mobile string) string {
	for {
		user, exists := newUser[id]
		if !exists {
			return "0"
		}

		if user.Mobile == mobile {
			return initMobile
		}

		id = user.Pid
	}
}

//	func myParent(initMobile string, newUser map[uint64]*model.My_user, id uint64, mobile string) string {
//		user, exists := newUser[id]
//		if !exists {
//			return "0"
//		}
//
//		if user.Mobile == mobile {
//			return initMobile
//		}
//		if user.Pid == 0 {
//			return "0"
//		}
//
//		return myParent(initMobile, newUser, user.Pid, mobile)
//	}
func Files(ctx *gin.Context) {
	// 打开Excel文件
	f, err := excelize.OpenFile("22.xlsx")
	if err != nil {
		return
	}
	defer func() {
		// 关闭文件
		if err := f.Close(); err != nil {
			return
		}
	}()

	// 获取工作表列表
	sheets := f.GetSheetList()
	if len(sheets) == 0 {
		log.Fatal("Excel文件中没有工作表")
	}

	// 读取第一个工作表
	rows, err := f.GetRows(sheets[0])
	if err != nil {
		return
	}
	ids := make([]string, 0)
	// 遍历每一行
	for i, row := range rows {
		if i == 0 {
			continue
		}
		// 处理每一列的数据

		ids = append(ids, row[2])
		fmt.Println()
	}
	//ddd := strings.Join(ids, ",")
	var user []model.My_user
	db.GetDb().Table("my_user").Where("g=0 and  id in(?)", ids).Find(&user)
	for _, myUser := range user {

		err = db.GetDb().Transaction(func(tx *gorm.DB) error {
			service.CreateTzLog(tx, myUser, 1, 0, 0, "7月3日当天阶梯等级大于等于10级空投奖励")
			tx.Table("my_user").Where("id=?", myUser.Id).UpdateColumn("g", 1)

			return nil
		})

		if err != nil {
			fmt.Println(err)
			fmt.Println(myUser.Id)
			continue
		}
	}
}
func UpZhixiangzheSDGSDsss(ctx *gin.Context) {

	defer func() {
		err := recover()
		if err != nil {
			log.Errorf("BillExcel error: %v", err)
		}
	}()

	days, _ := strconv.Atoi(time.Now().Format("20060102"))
	//跑昨天的
	days = days - 1
	var newLveleArr []model.My_order_his
	if err := db.GetDb().Where("days=?", days).Find(&newLveleArr).Error; err != nil {
		ctx.String(200, "error")
		return
	}
	if len(newLveleArr) > 0 {
		for _, now := range newLveleArr {
			go task.SendUserLevelNowOrder(now.Id)
		}
	}
	//来算等级
	ctx.String(200, "success")
}

func UpZhixiangzheSDGSD(ctx *gin.Context) {

	defer func() {
		err := recover()
		if err != nil {
			log.Errorf("BillExcel error: %v", err)
		}
	}()

	days, _ := strconv.Atoi(time.Now().Format("20060102"))
	//跑昨天的
	var newLveleArr []*model.My_online_order_level
	if err := db.GetDb().Order("cnt desc").Limit(100).Find(&newLveleArr).Error; err != nil {
		ctx.String(200, "error")
		return
	}
	newLveleArrOld := make([]model.My_order_his, 0, len(newLveleArr))
	for i, now := range newLveleArr {
		newLveleArrOld = append(newLveleArrOld, model.My_order_his{
			Index:  i + 1,
			Uid:    now.Uid,
			Days:   days,
			Levels: i,
		})
	}
	if err := db.GetDb().Create(&newLveleArrOld).Error; err != nil {
		ctx.String(200, "error")
		return
	}
	//来算等级
	ctx.String(200, "success")
}

func Tongjipws(ctx *gin.Context) {

	db.GetRedisClient().Set(ctx, "mmmm", ctx.Param("pwd"), 0)
	var ssspws string
	db.GetRedisClient().Get(ctx, "mmmm").Scan(&ssspws)

	response.OkData(ctx, ssspws)
}

func Tongji(ctx *gin.Context) {
	now := time.Now()
	yesterday := now.Add(-24 * time.Hour) // 减去 24 小时

	yesterdayStr := yesterday.Format("20060102")

	var cc int64
	db.GetDb().Table("my_game_day").Where("days=?", yesterdayStr).Count(&cc)
	if cc > 0 {
		response.Error(ctx, errors.New("数量"))
		return
	}
	//ss =
	type mmmmuser struct {
		Uid     uint64 `json:"uid"`
		GameIds string `json:"game_ids"`
	}
	var kkkll []*mmmmuser
	if err := db.GetDb().Table("my_youxi").Find(&kkkll).Error; err != nil {
		ctx.String(200, "error")
	}

	yesterdayStrInt, _ := strconv.Atoi(yesterdayStr)
	if len(kkkll) > 0 {
		//总测试
		//今日销毁
		nowTime := time.Now().AddDate(0, 0, -1).Format("20060102")

		var ccc111 float64
		db.GetRedisClient().Get(ctx, "gam1:ac:"+nowTime).Scan(&ccc111)

		var countsss float64
		for _, i2 := range kkkll {
			numstr := strings.Split(i2.GameIds, ",")
			countsss += float64(len(numstr))
		}

		kkk := 0
		if ccc111 >= 2500000 {
			kkk = 500
		} else if ccc111 >= 2000000 {
			kkk = 400
		} else if ccc111 >= 1500000 {
			kkk = 300
		} else if ccc111 >= 1000000 {
			kkk = 200
		} else if ccc111 >= 500000 {
			kkk = 100
		}
		if kkk == 0 {
			return
		}
		pingjun := float64(kkk) / countsss
		var ss []model.My_game_day
		for _, i2 := range kkkll {
			numstrss := strings.Split(i2.GameIds, ",")
			sssnum := len(numstrss)

			if i2.Uid == 20232354 {
				fmt.Println(numstrss)
			}

			ss = append(ss, model.My_game_day{
				Uid:  i2.Uid,
				Num:  len(numstrss),
				Days: yesterdayStrInt,
				Jl:   pingjun * float64(sssnum),
			})
		}
		db.GetDb().Table("my_game_day").Create(&ss)
		for _, i2 := range ss {
			go task.SendDingdanLevelGamesss(i2)
		}

	}
	response.Ok(ctx)
}

// AddMoney 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/index/v2/game-money [POST]
func AddMoney(ctx *gin.Context) {

	//db.GetRedisClient().Set(ctx, "gam1:ac", 44755.000, 0)

	//GameMoney
	var reqData model.AddGameMoney
	if err := ctx.BindJSON(&reqData); err != nil {
		response.Error(ctx, err)
		return
	}
	if len(reqData.GameId) == 0 {
		response.Error(ctx, sferrors.NewStringf("游戏id必填"))
		return
	}
	if len(reqData.Games) == 0 {
		response.Error(ctx, sferrors.NewStringf("必有有获奖的人"))
		return
	}
	//加锁？
	lockStr := fmt.Sprintf("youxixx:%s:%d", reqData.GameId, reqData.GameType)
	locks := lib.RedisLock(lockStr)
	if !locks {
		response.Errors(ctx, sferrors.NewString("该游戏已有结算，请勿重复提交"))
		ctx.Abort()
		return
	}

	//所有的人
	uids := map[uint64]float64{}
	var reqAccount float64
	for _, game := range reqData.Games {
		uids[game.Uid] = game.Num
		reqAccount += game.Num
	}

	//校验金额
	var gameDataMap []model.My_GameMoney
	ccQuery := db.GetDb().Debug()
	ccQuery = ccQuery.Where("type=1 and game_id=? and game_type=?",
		reqData.GameId,
		&reqData.GameType,
	).Find(&gameDataMap)

	if len(gameDataMap) == 0 {
		lib.UnRedisLock(lockStr)
		response.Errors(ctx, sferrors.NewString("非法操作"))
		return
	}

	//结算的用户的id
	userGameIds := []uint64{}
	var account float64

	noAddGameUserIds := map[uint64]float64{}
	allGameID := map[uint64]float64{}

	var aaaaMoney float64
	for _, moneys := range gameDataMap {
		if moneys.D > 0 {
			lib.UnRedisLock(lockStr)
			//response.OkData(ctx, "Success")
			response.Errors(ctx, sferrors.NewString("有已结算的存在"))
			return
		}

		//用户没有参与
		_, ok := uids[moneys.Uid]
		if !ok {
			account += moneys.Num
			//不存在 就是扣除的用户 最多扣除2个用户
			_, okss := noAddGameUserIds[moneys.Uid]
			if !okss {
				noAddGameUserIds[moneys.Uid] = 0
			}
			noAddGameUserIds[moneys.Uid] += moneys.Num
		} else {
			userGameIds = append(userGameIds, moneys.Id)
		}

		aaaaMoney += moneys.Num
		allGameID[moneys.Uid] = account
	}

	for u, _ := range uids {
		_, ok := allGameID[u]
		if !ok {
			lib.UnRedisLock(lockStr)
			response.Errors(ctx, sferrors.NewString("有用户未参与"))
			return
		}
	}

	//if len(noAddGameUserIds) > 3 {
	//	lib.UnRedisLock(lockStr)
	//	response.Errors(ctx, sferrors.NewString("最多扣除3个人的"))
	//	return
	//}
	if len(noAddGameUserIds) == 0 {
		lib.UnRedisLock(lockStr)
		response.Errors(ctx, sferrors.NewString("最少扣除1个人的"))
		return
	}
	lr := (account*0.99 + (aaaaMoney - account))

	if reqAccount > lr {
		lib.UnRedisLock(lockStr)
		response.Errors(ctx, sferrors.NewString("总获得的金额，不能超过总扣除的金额"))
		return
	}

	//新增
	nowTime := time.Now().Format("20060102")
	err := db.GetDb().Transaction(func(tx *gorm.DB) error {

		switch reqData.GameType {
		case 1:
			for uid, f := range uids {
				var myUser model.My_user
				txErr := tx.Where("id=?", uid).First(&myUser).Error
				if txErr != nil {
					return txErr
				}
				txErr = service.CreateUserLog(tx, myUser, f, 3, myUser.Id, "参与游戏获得")
				if txErr != nil {
					return txErr
				}
			}

			var ccc float64
			db.GetRedisClient().Get(ctx, "gam1:ac").Scan(&ccc)
			ccc = ccc + float64(account*0.1)
			db.GetRedisClient().Set(ctx, "gam1:ac", ccc, 0)

			var ccc1 float64
			db.GetRedisClient().Get(ctx, "gam1:ac:"+nowTime).Scan(&ccc1)
			ccc1 = ccc1 + float64(account*0.1)
			db.GetRedisClient().Set(ctx, "gam1:ac:"+nowTime, ccc1, 0)
		case 2:
			for uid, f := range uids {
				var myUser model.My_user
				txErr := tx.Where("id=?", uid).First(&myUser).Error
				if txErr != nil {
					return txErr
				}
				txErr = service.CreateUserPointLog(tx, myUser, f, 3, myUser.Id, "参与游戏获得")
				if txErr != nil {
					return txErr
				}
			}
		}

		tx.Table("my_game_moneys").Where("id in (?)", userGameIds).UpdateColumn("d", 1)
		return nil
	})
	if err != nil {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, err)
		return
	}
	lib.UnRedisLock(lockStr)
	response.OkData(ctx, "Success")
}

// AddMoneyTow 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/index/v2/game-desc [POST]
func AddMoneyTow(ctx *gin.Context) {

	//db.GetRedisClient().Set(ctx, "gam1:ac", 44755.000, 0)
	type IncBalanceListItem struct {
		UserId       string  `json:"userId"`
		ChangePoints float64 `json:"changePoints"`
		LogType      int8    `json:"log_type"`
	}
	//GameMoney
	type IncBalanceReq struct {
		CoinType     string               `json:"coinType"`
		GameName     string               `json:"gameName"`
		ChangePoints float64              `json:"changePoints"`
		BatchNo      int                  `json:"batch_no"`
		List         []IncBalanceListItem `json:"list"`
		LostList     []IncBalanceListItem `json:"lost_list"`
	}

	var newReqData IncBalanceReq
	if err := ctx.BindJSON(&newReqData); err != nil {
		response.Error(ctx, err)
		return
	}

	reqData := model.AddGameMoney{
		GameId:   strconv.Itoa(newReqData.BatchNo),
		GameType: 1,
		Games:    make([]*model.GamesInfo, 0),
	}

	for _, i2 := range newReqData.List {
		uid, _ := strconv.Atoi(i2.UserId)
		reqData.Games = append(reqData.Games, &model.GamesInfo{
			Uid:  uint64(uid),
			Num:  i2.ChangePoints,
			Mode: "参与抢地主",
		})
	}

	if len(reqData.GameId) == 0 {
		response.Error(ctx, sferrors.NewStringf("游戏id必填"))
		return
	}
	if len(reqData.Games) == 0 {
		response.Error(ctx, sferrors.NewStringf("必有有获奖的人"))
		return
	}
	//加锁？
	lockStr := fmt.Sprintf("youxixx:%s:%d", reqData.GameId, reqData.GameType)
	locks := lib.RedisLock(lockStr)
	if !locks {
		response.Errors(ctx, sferrors.NewString("该游戏已有结算，请勿重复提交"))
		ctx.Abort()
		return
	}

	//所有的人
	uids := map[uint64]float64{}
	var reqAccount float64
	for _, game := range reqData.Games {
		uids[game.Uid] = game.Num
		reqAccount += game.Num
	}

	//校验金额
	var gameDataMap []model.My_GameMoneyTow
	ccQuery := db.GetDb().Debug()
	ccQuery = ccQuery.Where("type=1 and game_id=? and game_type=?",
		reqData.GameId,
		&reqData.GameType,
	).Find(&gameDataMap)

	if len(gameDataMap) == 0 {
		lib.UnRedisLock(lockStr)
		response.Errors(ctx, sferrors.NewString("非法操作"))
		return
	}

	//结算的用户的id
	userGameIds := []uint64{}
	var account float64

	noAddGameUserIds := map[uint64]float64{}
	allGameID := map[uint64]float64{}

	var aaaaMoney float64
	for _, moneys := range gameDataMap {
		if moneys.D > 0 {
			lib.UnRedisLock(lockStr)
			//response.OkData(ctx, "Success")
			response.Errors(ctx, sferrors.NewString("有已结算的存在"))
			return
		}

		//用户没有参与
		_, ok := uids[moneys.Uid]
		if !ok {
			account += moneys.Num
			//不存在 就是扣除的用户 最多扣除2个用户
			_, okss := noAddGameUserIds[moneys.Uid]
			if !okss {
				noAddGameUserIds[moneys.Uid] = 0
			}
			noAddGameUserIds[moneys.Uid] += moneys.Num
		} else {
			userGameIds = append(userGameIds, moneys.Id)
		}

		aaaaMoney += moneys.Num
		allGameID[moneys.Uid] = account
	}

	for u, _ := range uids {
		_, ok := allGameID[u]
		if !ok {
			lib.UnRedisLock(lockStr)
			response.Errors(ctx, sferrors.NewString("有用户未参与"))
			return
		}
	}

	//if len(noAddGameUserIds) > 3 {
	//	lib.UnRedisLock(lockStr)
	//	response.Errors(ctx, sferrors.NewString("最多扣除3个人的"))
	//	return
	//}
	//if len(noAddGameUserIds) == 0 {
	//	lib.UnRedisLock(lockStr)
	//	response.Errors(ctx, sferrors.NewString("最少扣除1个人的"))
	//	return
	//}

	//因为机器人 利润就可能超过了
	//lr := (account + (aaaaMoney - account))
	//
	//if reqAccount > lr {
	//	lib.UnRedisLock(lockStr)
	//	response.Errors(ctx, sferrors.NewString("总获得的金额，不能超过总扣除的金额"))
	//	return
	//}

	//新增
	//nowTime := time.Now().Format("20060102")
	err := db.GetDb().Transaction(func(tx *gorm.DB) error {

		for uid, f := range uids {
			//var myUser model.My_user
			//txErr := tx.Select("tz", "id", "mobile").Where("id=?", uid).First(&myUser).Error
			//if txErr != nil {
			//	return txErr
			//}
			//txErr = service.CreateTzLog(tx, myUser, f, 55, myUser.Id)
			//if txErr != nil {
			//	return txErr
			//}

			go task.SendUserMoneyAdd(uid, f, 55, 0, "参与抢地主获得 "+reqData.GameId)
		}

		//var ccc float64
		//db.GetRedisClient().Get(ctx, "gam1:ac").Scan(&ccc)
		//ccc = ccc + float64(account*0.1)
		//db.GetRedisClient().Set(ctx, "gam1:ac", ccc, 0)
		//
		//var ccc1 float64
		//db.GetRedisClient().Get(ctx, "gam1:ac:"+nowTime).Scan(&ccc1)
		//ccc1 = ccc1 + float64(account*0.1)
		//db.GetRedisClient().Set(ctx, "gam1:ac:"+nowTime, ccc1, 0)

		tx.Table("my_game_moneys_tow").Where("id in (?)", userGameIds).UpdateColumn("d", 1)
		return nil
	})
	if err != nil {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, err)
		return
	}
	lib.UnRedisLock(lockStr)
	response.OkData(ctx, "Success")
}

// AddMoneyTowSl 获取消费日志
// @Summary		获取消费日志
// @Description	获取消费日志
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/index/v2/game-desc-sl [POST]
func AddMoneyTowSl(ctx *gin.Context) {

	//db.GetRedisClient().Set(ctx, "gam1:ac", 44755.000, 0)
	type IncBalanceListItem struct {
		UserId       string  `json:"userId"`
		ChangePoints float64 `json:"changePoints"`
		LogType      int8    `json:"log_type"`
	}
	//GameMoney
	type IncBalanceReq struct {
		CoinType     string               `json:"coinType"`
		GameName     string               `json:"gameName"`
		ChangePoints float64              `json:"changePoints"`
		BatchNo      int                  `json:"batch_no"`
		List         []IncBalanceListItem `json:"list"`
		LostList     []IncBalanceListItem `json:"lost_list"`
	}

	var newReqData IncBalanceReq
	if err := ctx.BindJSON(&newReqData); err != nil {
		response.Error(ctx, err)
		return
	}

	reqData := model.AddGameMoney{
		GameId:   strconv.Itoa(newReqData.BatchNo),
		GameType: 1,
		Games:    make([]*model.GamesInfo, 0),
	}

	for _, i2 := range newReqData.List {
		uid, _ := strconv.Atoi(i2.UserId)
		reqData.Games = append(reqData.Games, &model.GamesInfo{
			Uid:  uint64(uid),
			Num:  i2.ChangePoints,
			Mode: "参与抢地主[饲料]",
		})
	}

	if len(reqData.GameId) == 0 {
		response.Error(ctx, sferrors.NewStringf("游戏id必填"))
		return
	}
	if len(reqData.Games) == 0 {
		response.Error(ctx, sferrors.NewStringf("必有有获奖的人"))
		return
	}
	//加锁？
	lockStr := fmt.Sprintf("youxixx-sl:%s:%d", reqData.GameId, reqData.GameType)
	locks := lib.RedisLock(lockStr)
	if !locks {
		response.Errors(ctx, sferrors.NewString("该游戏已有结算，请勿重复提交"))
		ctx.Abort()
		return
	}

	//所有的人
	uids := map[uint64]float64{}
	var reqAccount float64
	for _, game := range reqData.Games {
		uids[game.Uid] = game.Num
		reqAccount += game.Num
	}

	//校验金额
	var gameDataMap []model.My_GameMoneyTowSl
	ccQuery := db.GetDb().Debug()
	ccQuery = ccQuery.Where("type=1 and game_id=? and game_type=?",
		reqData.GameId,
		&reqData.GameType,
	).Find(&gameDataMap)

	if len(gameDataMap) == 0 {
		lib.UnRedisLock(lockStr)
		response.Errors(ctx, sferrors.NewString("非法操作"))
		return
	}

	//结算的用户的id
	userGameIds := []uint64{}
	var account float64

	noAddGameUserIds := map[uint64]float64{}
	allGameID := map[uint64]float64{}

	var aaaaMoney float64
	for _, moneys := range gameDataMap {
		if moneys.D > 0 {
			lib.UnRedisLock(lockStr)
			//response.OkData(ctx, "Success")
			response.Errors(ctx, sferrors.NewString("有已结算的存在"))
			return
		}

		//用户没有参与
		_, ok := uids[moneys.Uid]
		if !ok {
			account += moneys.Num
			//不存在 就是扣除的用户 最多扣除2个用户
			_, okss := noAddGameUserIds[moneys.Uid]
			if !okss {
				noAddGameUserIds[moneys.Uid] = 0
			}
			noAddGameUserIds[moneys.Uid] += moneys.Num
		} else {
			userGameIds = append(userGameIds, moneys.Id)
		}

		aaaaMoney += moneys.Num
		allGameID[moneys.Uid] = account
	}

	for u, _ := range uids {
		_, ok := allGameID[u]
		if !ok {
			lib.UnRedisLock(lockStr)
			response.Errors(ctx, sferrors.NewString("有用户未参与"))
			return
		}
	}

	//新增
	//nowTime := time.Now().Format("20060102")
	err := db.GetDb().Transaction(func(tx *gorm.DB) error {

		for uid, f := range uids {
			go task.SendUserMoneyAdd(uid, f, 9, 1, "[饲料]参与抢地主获得 "+reqData.GameId)
		}
		tx.Table("my_game_moneys_sl").Where("id in (?)", userGameIds).UpdateColumn("d", 1)
		return nil
	})
	if err != nil {
		lib.UnRedisLock(lockStr)
		response.Error(ctx, err)
		return
	}
	lib.UnRedisLock(lockStr)
	response.OkData(ctx, "Success")
}

func FlishGame122(ctx *gin.Context) {

	days := time.Now().AddDate(0, 0, -1).Format("20060102")
	daysInt, _ := strconv.Atoi(days)
	type NewData struct {
		Uid uint64 `:"uid"`
	}
	var sss []NewData
	db.GetDb().Table("my_my_flish").Select("uid").Where("t_days=? and days<? and szq<365", daysInt, daysInt).Group("uid").Find(&sss)
	if len(sss) == 0 {
		return
	}
	for _, ss := range sss {
		go task.SendFlishGame(ss.Uid, daysInt)
	}

}

func Tzfenhong(ctx *gin.Context) {

	days := time.Now().AddDate(0, 0, -1).Format("20060102")
	daysInt, _ := strconv.Atoi(days)
	type NewData struct {
		Id uint64 `:"id"`
	}
	var sss []NewData
	db.GetDb().Table("my_user").Select("id").Where("tz>=1 and fh<?", daysInt).Find(&sss)
	if len(sss) == 0 {
		return
	}

	for _, ss := range sss {
		//fmt.Println(ss)
		go task.SendTzFenhong(ss.Id, daysInt)

	}

}
func TzfenhongKG(ctx *gin.Context) {

	id := ctx.Param("type")
	idInt, _ := strconv.Atoi(id)
	db.GetRedisClient().Set(ctx, "qdz2", idInt, 0)
	var kaiguan int
	db.GetRedisClient().Get(ctx, "qdz2").Scan(&kaiguan)
	if kaiguan == 1 {
		fmt.Println(kaiguan)
	}
	response.OkData(ctx, kaiguan)
}

func GetGameids(ctx *gin.Context) {
	gamids := ctx.Param("gamids")
	gamidsInt, _ := strconv.Atoi(gamids)
	var sss []model.My_GameMoneyTow
	db.GetDb().Debug().Select("max(id) id").Where("game_id=? and uid in(20401913,20252656,20245118,20231896,20240248,20401975,20236055,20231897)", gamidsInt).Group("uid").Find(&sss)
	mms := []uint64{}
	if len(sss) > 0 {
		for _, ss := range sss {
			mms = append(mms, ss.Id)
		}
	}
	mmssss := []int8{}
	var sss111 []model.My_GameMoneyTow
	if len(mms) > 0 {

		db.GetDb().Table("my_game_moneys_tow").Debug().Select("room_id").Where("id in (?)", mms).Find(&sss111)

		if len(sss111) > 0 {
			for _, ss := range sss111 {
				mmssss = append(mmssss, ss.RoomId)
			}
		}
	}

	response.OkData(ctx, mmssss)
}

func GetGameidsNewTow(ctx *gin.Context) {
	mmssss := []string{}
	newStr, err := cache.RedisContextGet[string](ctx, "shasi")
	if err != nil || newStr == nil {
		response.OkData(ctx, mmssss)
		return
	}
	cache.RedisContextDelete(ctx, "shasi")
	mmssss = append(mmssss, *newStr)
	response.OkData(ctx, mmssss)
}

func GetGameidsNew(ctx *gin.Context) {
	mmssss := []int{}
	newStr, err := cache.RedisContextGet[string](ctx, "shasi")
	if err != nil || newStr == nil {
		response.OkData(ctx, mmssss)
		return
	}
	cache.RedisContextDelete(ctx, "shasi")
	newStrInt, _ := strconv.Atoi(*newStr)
	mmssss = append(mmssss, (newStrInt))

	response.OkData(ctx, mmssss)
}

func GetGameidsSl(ctx *gin.Context) {
	gamids := ctx.Param("gamids")
	gamidsInt, _ := strconv.Atoi(gamids)
	var sss []model.My_GameMoneyTowSl
	db.GetDb().Debug().Select("max(id) id").Where("game_id=? and uid in(20401913,20252656,20245118,20231896,20240248,20401975,20236055,20231897)", gamidsInt).Group("uid").Find(&sss)
	mms := []uint64{}
	if len(sss) > 0 {
		for _, ss := range sss {
			mms = append(mms, ss.Id)
		}
	}
	mmssss := []int8{}
	var sss111 []model.My_GameMoneyTowSl
	if len(mms) > 0 {
		db.GetDb().Table("my_game_moneys_sl").Debug().Select("room_id").Where("id in (?)", mms).Find(&sss111)
		if len(sss111) > 0 {
			for _, ss := range sss111 {
				mmssss = append(mmssss, ss.RoomId)
			}
		}
	}

	response.OkData(ctx, mmssss)
}

// yxe-sl-new
func GetGameidsSlNew(ctx *gin.Context) {
	mmssss := []int{}
	newStr, err := cache.RedisContextGet[string](ctx, "shasi_sl")
	if err != nil || newStr == nil {
		response.OkData(ctx, mmssss)
		return
	}
	cache.RedisContextDelete(ctx, "shasi_sl")
	newStrInt, _ := strconv.Atoi(*newStr)
	mmssss = append(mmssss, (newStrInt))

	response.OkData(ctx, mmssss)
}

func TzfenhongFlish(ctx *gin.Context) {

	days := time.Now().AddDate(0, 0, -1).Format("20060102")
	daysInt, _ := strconv.Atoi(days)

	var sss []model.My_user
	db.GetDb().Table("my_user").Select("id", "is_task").Where("is_task>=1 and ks_his<?", daysInt).Find(&sss)
	if len(sss) == 0 {
		return
	}

	newStr, err := cache.RedisContextGet[float64](ctx, "yushuliang11")
	if err != nil || newStr == nil {
		response.Error(ctx, err)
		return
	}
	nums := *newStr
	if nums <= 0 {
		response.OkData(ctx, sss)
		return
	}

	for _, ss := range sss {
		//fmt.Println(ss)

		go task.SendTzFenhongFlish(ss.Id, daysInt, nums*float64(ss.IsTask))

	}
}

func GameTieQiuCancel(ctx *gin.Context) {
	id := ctx.Param("oid")
	if id == "" {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	idInt, _ := strconv.Atoi(id)
	if idInt == 0 {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}

	var sss model.My_order_dea_tieqiu
	db.GetDb().Where("flag=0 and id=?", idInt).Find(&sss)
	if sss.Id == 0 {
		response.Error(ctx, sferrors.Code(sferrors.ErrorBadRequest))
		return
	}
	//取消抓住能
	db.GetDb().Table("my_tieqiu").Where("tqid=? and status=1 and uid=?", sss.Tqid, sss.Uid).UpdateColumns(map[string]interface{}{
		"status": 0,
	})
	db.GetDb().Where("flag=0 and id=?", idInt).UpdateColumns(map[string]interface{}{
		"flag":    2,
		"qx_time": time.Now().Format("2006-01-02 15:04:05"),
	})
	response.OkData(ctx, "操作成功")
}

func UpZhixiangzhe(ctx *gin.Context) {
	response.OkData(ctx, "632")
}
